<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :destroy-on-close="true"
    @ok="handleSubmit"
    width="800px"
    ok-text="保存"
    title="配置"
  >
    <BasicForm @register="registerForm">
      <template #seriesSlot>
        <div class="h-14" v-for="item in seriesList" :key="item.key">
          <BasicForm @register="item.Form[0]">
            <template #deleteSlot>
              <a-button type="link" danger @click="handleDelete(item.key)">删除</a-button>
            </template>
          </BasicForm>
        </div>
        <a-button class="mt-2" @click="handleAdd">新增数据源</a-button>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormProps } from '/@/components/Form';
  import { getEntityDeviceList } from '/@/api/thingsborad/entity/entity';
  import { useDebounceFn } from '@vueuse/shared';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    schemas,
    seriesFormList,
    FormItem,
    seriesFormSchema,
    baseFormConfig,
  } from './settingModal.data';
  import { ref, watch } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { buildUUID } from '/@/utils/uuid';
  import { getEntityKeys } from '/@/api/thingsborad/dashboards/dashboard';
  import { getDeviceInfo } from '/@/api/thingsborad/entity/entity';

  const emits = defineEmits(['success']);
  const seriesList = ref<Array<FormItem>>(cloneDeep(seriesFormList));
  const deviceId = ref<string>('');
  const flag = ref<boolean>(true);
  const entityName = ref<string>('');
  const defaultOptions = ref<any>();
  const defaultWsParams = ref<any>();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (widgetInfo) => {
    setModalProps({
      ...modalStyleSetting,
    });
    updateSchema({
      field: 'deviceId',
      label: '设备',
      component: 'ApiSelect',
      componentProps: () => {
        const params = ref({
          pageSize: 50,
          page: 0,
          textSearch: entityName.value,
          sortProperty: 'name',
          sortOrder: 'ASC',
        });
        return {
          placeholder: '请选择设备',
          listHeight: 160,
          api: getEntityDeviceList,
          params: params.value,
          resultField: 'data',
          labelField: 'name',
          valueField: 'id',
          objectToJson: true,
          showSearch: true,
          onSearch: useDebounceFn((e) => {
            params.value.textSearch = e;
          }, 300),
          onChange: (e: string) => {
            if (e) {
              deviceId.value = e;
            } else {
              params.value.textSearch = '';
            }
          },
          immediate: true,
        };
      },
      ifShow: ({ values }) => values.type === 'device',
      required: true,
    });
    const { options, wsParams } = widgetInfo;
    defaultOptions.value = options;
    defaultWsParams.value = wsParams;
    if (options && wsParams) {
      entityName.value = (await getDeviceInfo(wsParams.singleEntity.id)).name;
      setFieldsValue({
        deviceId: JSON.stringify(wsParams.singleEntity),
        chartType: options.series[0].type,
      });
      seriesList.value = [];
      options.series.forEach(() => {
        seriesList.value.push({
          key: buildUUID(),
          Form: useForm(
            Object.assign(
              { schemas: seriesFormSchema },
              {
                ...baseFormConfig,
                labelCol: {
                  style: {
                    marginTop: '20px',
                  },
                },
              },
            ) as FormProps,
          ),
        });
      });
      setTimeout(() => {
        seriesList.value.forEach((item, index) => {
          const { setFieldsValue } = item.Form[1];
          
          setFieldsValue({
            key: JSON.stringify(wsParams.keys[index]),
            name: options.series[index].name,
            color: options.series[index].itemStyle.color,
          });
        });
      }, 10);
    }
  });
  const [registerForm, { updateSchema, validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const handleAdd = () => {
    seriesList.value.push({
      key: buildUUID(),
      Form: useForm(
        Object.assign(
          { schemas: seriesFormSchema },
          {
            ...baseFormConfig,
            labelCol: {
              style: {
                marginTop: '20px',
              },
            },
          },
        ) as FormProps,
      ),
    });
  };
  const handleDelete = (key: string) => {
    seriesList.value = seriesList.value.filter((item) => item.key !== key);
  };
  const updateKeySchema = (nVal: any) => {
    seriesList.value.forEach((item, index) => {
      const { updateSchema, setFieldsValue } = item.Form[1];
      setTimeout(() => {
        
        updateSchema({
          field: 'key',
          componentProps: {
            placeholder: '请选择数据键',
            listHeight: 160,
            api: getEntityKeys,
            params: {
              payload: {
                entityFilter: {
                  type: 'singleEntity',
                  singleEntity: nVal && JSON.parse(nVal),
                },
                pageLink: {
                  pageSize: 100,
                  page: 0,
                  sortOrder: {
                    key: {
                      type: 'ENTITY_FIELD',
                      key: 'createdTime',
                    },
                    direction: 'DESC',
                  },
                },
              },
              query: {
                attributes: true,
                timeseries: true,
              },
            },
            isDashBoard: true,
            showSearch: true,
            alwaysLoad: true,
            immediate: true,
          },
        });
      }, 10);
    });
  };

  watch(
    () => deviceId.value,
    async (nVal) => {
      updateKeySchema(nVal);
      // setTimeout(() => {
      //   seriesList.value.forEach((item, index) => {
      //     const { setFieldsValue } = item.Form[1];
      //     
      //     setFieldsValue({
      //       key: JSON.stringify(defaultWsParams.value.keys[index]),
      //       name: defaultOptions.value.series[index].name,
      //       color: defaultOptions.value.series[index].itemStyle.color,
      //     });
      //   });
      // }, 10);
    },
    {
      immediate: false,
      deep: true,
    },
  );
  watch(
    () => seriesList.value,
    () => {
      updateKeySchema(deviceId.value);
    },
    {
      immediate: false,
      deep: true,
    },
  );

  const handleSubmit = async () => {
    flag.value = !flag.value;
    let values = {};
    let series: Array<any> = [];
    const value = await validate();
    Object.assign(values, value);
    for (const item in seriesList.value) {
      const { validate } = seriesList.value[item].Form[1];
      const value = await validate();
      series.push(value);
    }
    Object.assign(values, { series });
    emits('success', values);
    closeModal();
  };
</script>
